global.ReadableStream = require('stream').Readable;
const express = require('express')
const cors = require('cors')
const mysql = require('mysql2')
const crypto = require('crypto')
const cheerio = require('cheerio')
const multer = require('multer');
const formidable = require('formidable')
const path = require('path')
const fs = require('fs')
const tool = require('./tool')
const xlsx = require('xlsx')
const http = require('http')
const axios = require('axios')
const QRCode = require('qrcode')

// const connectionConfig = {
//     host: 'localhost',
//     user: 'root',
//     password: 'root',
//     database: 'gmnote',
//     port: 3306
// }

const connectionConfig = {
    host: '127.0.0.1',
    user: 'root',
    password: 'Catiouszty2004_',
    database: 'gmnote',
    port: 3306,
    charset: 'utf8mb4'
}



const config = {
    port: 1000,
    prefix: '/api'
}

const connection = mysql.createConnection(connectionConfig);

console.clear()

//连接数据库
function connectDatabase() {
    return new Promise((resolve, reject) => {
        connection.connect(err => {
            return resolve(err == null ? 'OK' : err.toString())
        })
    })
}

function execSQL(SQL) {
    return new Promise((resolve, reject) => {
        connection.query(SQL, (error, results, fields) => {
            if (error) {
                console.log(error)
                // connection.query(`insert into log_sql(\`sql\`, status, results, time) values('${getInsertIntoSQLString(SQL)}',0,${'服务器内部错误'},'${(new Date()).toString()}')`)
                return reject()
            }
            // connection.query(`insert into log_sql(\`sql\`, status, results, time) values('${getInsertIntoSQLString(SQL)}',1,${JSON.stringify(results)},'${(new Date()).toString()}')`, (error1, results1, field1) => {
            //     console.log(error1)
            // })
            return resolve(results)
        })
    })
}

async function main() {
    try {
        console.clear()
        let re = await connectDatabase()
        if (re != 'OK') {
            console.log('gmnote server 未能正常启动，原因：' + re)
            process.exit(0)
        }
        const app = express();
        app.use(express.json())
        app.use(cors())
        const storage = multer.diskStorage({
            destination: 'files/',
            filename: function (req, file, cb) {
                const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1E9);
                const fileExtension = path.extname(file.originalname);
                cb(null, file.fieldname + '-' + uniqueSuffix + fileExtension);
            }
        })
        const upload = multer({ storage: storage })
        app.get(config.prefix + '/note_list', async (req, res) => {
            try {
                let re = await execSQL(`select * from note`)
                res.send({
                    status: 1,
                    data: re,
                    content: '成功'
                })
            } catch (error) {
                res.send({
                    status: 0,
                    content: '服务器内部错误'
                })
            }
        })
        app.get(config.prefix + '/note/:id', async (req, res) => {
            try {
                console.log(req.params)
                let re = await execSQL(`select * from note where id = ${req.params.id}`)
                if (re.length != 0) {
                    res.send({
                        status: 1,
                        content: '成功',
                        data: re[0]
                    })
                } else {
                    res.send({
                        status: 0,
                        content: '无此笔记'
                    })
                }
            } catch (error) {
                res.send({
                    status: 0,
                    content: '服务器内部错误'
                })
            }
        })
        app.post(config.prefix + '/save_note/:id', async (req, res) => {
            try {
                // 获取 URL 参数
                const noteId = req.params.id;

                // 获取请求体中的参数
                let noteData = req.body;
                noteData.time = (new Date()).toString()
                console.log('Received note data:', noteData); // 打印接收到的参数

                await execSQL(`update note set title = '${noteData.title}', content = '${noteData.content}', time = '${noteData.time}' where id = ${noteData.id}`)

                // 这里可以添加数据库操作，比如检查是否存在该笔记
                // let re = await execSQL(`select * from note where id = ${noteId}`);
                // if (re.length !== 0) {
                //     res.send({
                //         status: 1,
                //         content: '成功',
                //         data: re[0]
                //     });
                // } else {
                //     res.send({
                //         status: 0,
                //         content: '无此笔记'
                //     });
                // }

                // 发送响应
                res.send({
                    status: 1,
                    content: '成功', // 或者其他需要的内容
                });
            } catch (error) {
                console.error(error); // 打印错误信息
                res.send({
                    status: 0,
                    content: '服务器内部错误'
                });
            }
        })
        app.post(config.prefix + '/delete_note/:id', async (req, res) => {
            try {
                // 获取 URL 参数
                const noteId = req.params.id;

                // 获取请求体中的参数
                let noteData = req.body;
                noteData.time = (new Date()).toString()
                console.log('Received note data:', noteData); // 打印接收到的参数

                await execSQL(`delete from note where id = ${noteId}`)

                // 这里可以添加数据库操作，比如检查是否存在该笔记
                // let re = await execSQL(`select * from note where id = ${noteId}`);
                // if (re.length !== 0) {
                //     res.send({
                //         status: 1,
                //         content: '成功',
                //         data: re[0]
                //     });
                // } else {
                //     res.send({
                //         status: 0,
                //         content: '无此笔记'
                //     });
                // }

                // 发送响应
                res.send({
                    status: 1,
                    content: '成功', // 或者其他需要的内容
                });
            } catch (error) {
                console.error(error); // 打印错误信息
                res.send({
                    status: 0,
                    content: '服务器内部错误'
                });
            }
        })
        app.get(config.prefix + '/new_note', async (req, res) => {
            try {
                let re = await execSQL(`select id from note`)
                re.sort((a, b) => {
                    return a.id - b.id
                })
                let id = re[re.length - 1].id + 1
                await execSQL(`insert into note values(${id},'新建笔记','','${(new Date()).toString()}')`)
                // 发送响应
                res.send({
                    status: 1,
                    content: '成功', // 或者其他需要的内容
                    data: id
                });
            } catch (error) {
                console.error(error); // 打印错误信息
                res.send({
                    status: 0,
                    content: '服务器内部错误'
                });
            }
        })
        app.post(config.prefix + '/file/upload', upload.single('file'), async (req, res) => {
            if (!req.file) {
                res.status(400).json({ error: '上传失败' });


                clog('上传文件', undefined, '', '失败', data)
            } else {
                res.json({
                    status: 1,
                    content: '上传成功',
                    results: req.file.filename
                })


                clog('上传文件', undefined, req.file.filename, '成功', data)
            }
        })
        app.get(config.prefix + '/file/download/:filename', async (req, res) => {
            const filename = req.params.filename;
            if (filename.indexOf('%b64%') != -1) {
                let re = await execSQL("select data from file where name = '" + filename + "'")
                if (re.length == 0) {
                    res.send('')
                    return
                }
                re = re[0].data
                res.setHeader('Content-Type', `image/jpeg`);
                res.send(re)
                return
            }
            const filePath = path.join('files', filename);
            if (!fs.existsSync(filePath)) {
                return res.status(404).json({
                    status: 0,
                    content: '无此文件'
                });
            }
            res.setHeader('Content-Disposition', `filename=${filename}`);
            const fileStream = fs.createReadStream(filePath);
            fileStream.pipe(res);
        })
        app.use(express.json({ limit: '50mb' }))
        app.use(express.urlencoded({ extended: true, limit: '50mb' }))
        app.listen(config.port, async () => {
            console.log('\x1b[32mgmnote Server Started.\x1b[37m')
            console.log('port:' + config.port.toString())
        })
    } catch (error) {
        console.log('main函数里的错误：', error)
    }
}

main()